﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
using XMK.Framework.DataAccess;
using XMK.Utils;
using System.Reflection;
using System.Web;

namespace XMK.Framework.Config
{
    /// <summary>
    /// 
    /// </summary>
    public static class ConfigHelper
    {
        private static readonly string AJAXHANDLERMAPPINGFILEPATH = "AjaxHandlerMappingFilePath";
        private static readonly string AJAXDataHANDLERMAPPINGFILEPATH = "AjaxDataMappingFilePath";
        private static readonly string SPMAPPINGFILEPATH = "SpMappingFilePath";
        /// <summary>
        /// 根据配置文件获取数据库实现
        /// </summary>
        /// <param name="dbName">Web.Config的connectionStrings配置节的name</param>
        /// <returns>数据库实现类</returns>
        public static DbProvider GetDbProvider(string dbName)
        {
            ConnectionStringSettings settings = ConfigurationManager.ConnectionStrings[dbName];
            if (settings == null)
                throw new Exception(String.Format(ErrorResource.ConnectionStringNotFound, dbName));
            string dbProviderName = settings.ProviderName;
            if (string.IsNullOrEmpty(settings.ProviderName))
                return new SqlDbProvider(settings.ConnectionString);
            return (DbProvider)ReflectionHelper.CreateInstance(Assembly.GetExecutingAssembly().FullName, dbProviderName, new Object[] { settings.ConnectionString });
        }
        /// <summary>
        /// 自动映射业务数据层文件
        /// </summary>
        internal static string MappingDataFilePath
        {
            get
            {
                string file = Utils.ConfigHelper.GetAppSettingValue(AJAXDataHANDLERMAPPINGFILEPATH, "App_Data/AjaxDataMapping.xml");
                if (!string.IsNullOrEmpty(file))
                    return HttpRuntime.AppDomainAppPath + file;
                return null;
            }
        }
        /// <summary>
        /// 自动映射业务层文件
        /// </summary>
        internal static string MappingFilePath
        {
            get
            {
                string file = Utils.ConfigHelper.GetAppSettingValue(AJAXHANDLERMAPPINGFILEPATH, "App_Data/AjaxMapping.xml");
                if (!string.IsNullOrEmpty(file))
                    return HttpRuntime.AppDomainAppPath + file;
                return null;
            }
        }
        /// <summary>
        /// 自动映射数据层文件
        /// </summary>
        internal static string SpMappingFilePath
        {
            get
            {
                string file = Utils.ConfigHelper.GetAppSettingValue(SPMAPPINGFILEPATH, "App_Data/SpMapping.xml");
                if (!string.IsNullOrEmpty(file))
                {
                    return AppDomain.CurrentDomain.BaseDirectory + file;
                    //return HttpRuntime.AppDomainAppPath + file;
                }                    
                return null;
            }
        }
    }
}
